package com.yuexun.dhdoctor.module.email.ui;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;

import com.yuexun.dhdoctor.R;
import com.yuexun.dhdoctor.base.BaseKJActivity;
import com.yuexun.dhdoctor.config.AppConfig;
import com.yuexun.dhdoctor.module.Contract.bean.People;
import com.yuexun.dhdoctor.module.commun.adapter.AddMemberAdapter;
import com.yuexun.dhdoctor.module.commun.ui.Act_Choice_Member;
import com.yuexun.dhdoctor.module.email.adapter.MailFileAdapter;
import com.yuexun.dhdoctor.module.email.bean.MailFileDataBean;
import com.yuexun.dhdoctor.module.email.bean.SendBean;
import com.yuexun.dhdoctor.module.email.bean.UploadBean;
import com.yuexun.dhdoctor.module.email.model.impl.SendModel;
import com.yuexun.dhdoctor.module.email.model.impl.UploadModel;
import com.yuexun.dhdoctor.module.email.presenter.ISendPresenter;
import com.yuexun.dhdoctor.module.email.presenter.IUploadPresenter;
import com.yuexun.dhdoctor.module.email.presenter.impl.SendPresenter;
import com.yuexun.dhdoctor.module.email.presenter.impl.UploadPresenter;
import com.yuexun.dhdoctor.module.email.ui.view.ISendView;
import com.yuexun.dhdoctor.module.email.ui.view.IUploadView;
import com.yuexun.dhdoctor.util.GetPathFromUri4kitkat;
import com.yuexun.dhdoctor.widget.ActionSheetDialog;
import com.yuexun.dhdoctor.widget.FixedSwipeListView;
import com.yuexun.dhdoctor.widget.UploadDialog;

import org.kymjs.kjframe.ui.ViewInject;
import org.kymjs.kjframe.utils.PreferenceHelper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * Created by work-jx on 2016/8/1.
 */
public class Act_SendMail extends BaseKJActivity implements ISendView, IUploadView {
    @Bind(R.id.grid)
    GridView grid;
    @Bind(R.id.sendmail_title_edt)
    EditText sendmailTitleEdt;
    @Bind(R.id.sendmail_cintent_edt)
    EditText sendmailCintentEdt;
    @Bind(R.id.sendmail_file_list)
    FixedSwipeListView sendmailFileList;

    private ArrayList<People> usersBeans_origin = new ArrayList<>();

    private AddMemberAdapter adapter;

    private ISendPresenter presenter;
    private IUploadPresenter presenter_upload;

    private UploadDialog uploadDialog;

    private ArrayList<MailFileDataBean> mailFileDataBeans = new ArrayList<>();
    private MailFileAdapter fileAdapter;

    //附件原路径
    private String img_path;

    @Override
    public void setRootView() {
        setContentView(R.layout.act_sendmail);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        super.initData();
        uploadDialog = new UploadDialog(this);
        presenter = new SendPresenter(new SendModel(), this);
        presenter_upload = new UploadPresenter(new UploadModel(), this);
    }

    private void setGridView() {

        int size = usersBeans_origin.size();

        int length = 80;

        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        float density = dm.density;
        int gridviewWidth = (int) (size * (length + 8) * density);
        int itemWidth = (int) (length * density);

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                gridviewWidth, LinearLayout.LayoutParams.FILL_PARENT);
        grid.setLayoutParams(params); // 重点
        grid.setColumnWidth(itemWidth); // 重点
        grid.setHorizontalSpacing(5); // 间距
        grid.setStretchMode(GridView.NO_STRETCH);
        grid.setNumColumns(size); // 重点

        adapter = new AddMemberAdapter(grid, usersBeans_origin, R.layout.item_send_addmember);
        grid.setAdapter(adapter);
    }

    @OnClick({R.id.back, R.id.sendmail_send, R.id.iv_add_sendmember, R.id.sendmail_add_attachment})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.sendmail_send:
                if (usersBeans_origin.size() != 0 && !"".equals(sendmailTitleEdt.getText().toString()) && !"".equals(sendmailCintentEdt.getText().toString())) {
                    submitDialog();
                } else {
                    ViewInject.toast("请检查标题,正文,人员是否填写");
                }
                break;
            case R.id.iv_add_sendmember:
//                Bundle bundle = new Bundle();
//                Intent intent = new Intent(this, Act_Choice_People.class);
//                bundle.putSerializable("persons", usersBeans_origin);
//                intent.putExtras(bundle);
//                aty.startActivityForResult(intent, 1);
                Bundle bundle = new Bundle();
                Intent intent = new Intent(this, Act_Choice_Member.class);
                bundle.putSerializable("persons", usersBeans_origin);
                bundle.putString("title", "");
                bundle.putInt("isSelectMe", 1);
                bundle.putString("type", "多选");
                intent.putExtras(bundle);
                aty.startActivityForResult(intent, 1);
                break;
            case R.id.sendmail_add_attachment:
                select_file();
                break;
        }
    }

    private void select_file() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");//设置类型，我这里是任意类型，任意后缀的可以这样写。
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(intent, 1);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode) {
            case 10000:
                usersBeans_origin = (ArrayList<People>) data.getExtras().getSerializable("persons");
                setGridView();
                break;
            case Activity.RESULT_OK:
                Uri uri = data.getData();//得到uri，后面就是将uri转化成file的过程。
                img_path = GetPathFromUri4kitkat.getPath(this, uri);
                presenter_upload.uploadFile(img_path);
                break;
            default:
                break;
        }
    }


    @Override
    public void sendMail(SendBean s) {
        if (s.getStatus().equals("200")) {
            ViewInject.toast("发送成功");
            finish();
        } else {
            ViewInject.toast("发送失败");
        }
    }

    @Override
    public void uploadDialogStatus(int status) {
        switch (status) {
            case AppConfig.SHOW_DIALOG:
                uploadDialog.setCanceledOnTouchOutside(false);
                uploadDialog.show();
                break;
            case AppConfig.DISMISS_DIALOG:
                uploadDialog.dismiss();
                break;

        }
    }

    @Override
    public void updateFile(UploadBean uploadBean) {
        if (mailFileDataBeans.size() == 0) {
            uploadBean.getData().get(0).setFileUrl(img_path);
            mailFileDataBeans.add(uploadBean.getData().get(0));
            fileAdapter = new MailFileAdapter(this, mailFileDataBeans, true);
            sendmailFileList.setAdapter(fileAdapter);
        } else {
            uploadBean.getData().get(0).setFileUrl(img_path);
            mailFileDataBeans.add(uploadBean.getData().get(0));
            fileAdapter.notifyDataSetChanged();
        }
    }

    private void submitDialog() {
        new ActionSheetDialog(aty)
                .builder()
                .setCancelable(true)
                .setCanceledOnTouchOutside(false)
                .setTitle("确认发送")
                .addSheetItem("存草稿", ActionSheetDialog.SheetItemColor.Blue,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                Submit(2);
                            }
                        })
                .addSheetItem("发送", ActionSheetDialog.SheetItemColor.Red,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                Submit(1);
                            }
                        }).show();
    }

    private void Submit(int type) {
        StringBuilder ids = new StringBuilder();
        StringBuilder name = new StringBuilder();
        for (int i = 0; i < usersBeans_origin.size(); i++) {
            ids.append(usersBeans_origin.get(i).getUserId()).append(";");
            name.append(usersBeans_origin.get(i).getUserName()).append(";");
        }
        Map<String, String> params = new HashMap<>();
        params.put("sessionUuid", PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.SESSION_ID));
        params.put("type", type + "");
        params.put("title", sendmailTitleEdt.getText().toString());
        params.put("content", sendmailCintentEdt.getText().toString());
        params.put("recipients", name.toString());
        params.put("recipients_ids", ids.toString());
        if (mailFileDataBeans.size() > 0) {
            String file = mailFileDataBeans.get(0).getFileUuid();
            for (int i = 1; i < mailFileDataBeans.size(); i++) {
                file = file + ";" + mailFileDataBeans.get(i).getFileUuid();
            }
            params.put("fileURL", file);
        }
        presenter.sendMail(params);
    }
}
